import { businessRouter, detailRouter } from "@/router/index";
import router from "_my/router/index";
import layout from "_my/layout";
export const initRouter = () => {
  menuTree(JSON.parse(sessionStorage.getItem("menu")), router);
  const str = sessionStorage.getItem("menu");
  const authorityRouter = [];
  detailRouter.forEach((item) => {
    if (str.indexOf(`"path":"/${item.parent}"`) !== -1) {
      router.addRoute({
        path: "/",
        component: layout,
        redirect: "/home",
        children: [item],
      });
      authorityRouter.push(item);
    }
  });
  sessionStorage.setItem("authorityRouter", JSON.stringify(authorityRouter));
  router.addRoute({
    path: "/*",
    name: "404",
    meta: { title: "页面走丢了" },
    component: () =>
      import(/* webpackChunkName: "login-login" */ "_my_c/404/404.vue"),
  });
};
export const menuTree = (data, target) => {
  if (!data) return;
  data.forEach((item) => {
    if (item.children.length > 0) {
      menuTree(item.children, target);
    } else {
      const component =
        businessRouter.find((item1) => "/" + item1.path === item.path) || item;
      if (component.component) {
        component.path = "/" + component.path;
        component.meta = { title: item.title };
        const routes = {
          path: "/",
          component: layout,
          redirect: "/home",
          children: [component],
        };
        target.addRoute(routes);
      } else {
        router.addRoute({
          path: component.path,
          name: "403",
          component: () =>
            import(/* webpackChunkName: "login-login" */ "_my_c/404/404.vue"),
        });
      }
    }
  });
};
